package com.cjb.cloudsystem.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.cjb.common.exception.ServerException;

import java.util.HashMap;
import java.util.Optional;

/**
 * @Author chenjinbin
 * @Package IntelliJ IDEA
 * @Class SysLogLoginConvert
 * @Date 2024-01-25 下午3:52
 */
public class SysLogLoginStatusConvert implements Converter<Integer> {
    // map映射
    private static final HashMap<Integer, String> GENDER_MAP = new HashMap<>() {{
        put(0, "失败");
        put(1, "成功");
    }};

    private static final HashMap<String, Integer> GENDER_REVERSE_MAP = new HashMap<>() {{
        put("失败", 0);
        put("成功", 1);
    }};

    @Override
    public Class<Integer> supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty,
                                     GlobalConfiguration globalConfiguration) throws Exception {
        if (cellData.getStringValue() != null) {
            // 使用Optional进行安全获取映射值
            return Optional.ofNullable(GENDER_REVERSE_MAP.get(cellData.getStringValue()))
                    .orElseThrow(() -> new ServerException("Invalid gender value: " + cellData.getStringValue()));
            // 或者返回默认值
            // return Optional.ofNullable(GENDER_REVERSE_MAP.get(cellData.getStringValue()))
            //         .orElse(DEFAULT_GENDER_VALUE); // DEFAULT_GENDER_VALUE 是你自定义的默认值
        }
        return -1; // 这里可以继续保留默认行为或者也使用Optional处理
    }

    @Override
    public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty,
                                       GlobalConfiguration globalConfiguration) {
        // 使用Optional进行安全获取映射值
        return new CellData(Optional.ofNullable(GENDER_MAP.get(value))
                .orElseThrow(() -> new ServerException("Invalid gender code: " + value)));
        // 或者返回默认值
        // return new CellData(Optional.ofNullable(GENDER_MAP.get(value))
        //         .orElse(DEFAULT_GENDER_STRING)); // DEFAULT_GENDER_STRING 是你自定义的默认字符串
    }
}
